<!-- 文件: TransactionsCrud.vue -->
<template>
  <el-container>
    <el-main>
      <el-card>
        <template #header>
          <div class="header">
            <h2>交易管理</h2>
            <el-button type="primary" @click="handleCreateClick">新增交易</el-button>
          </div>
        </template>

        <!-- 查询条件 -->
        <el-form :model="searchParams" inline class="search-form">
          <el-form-item label="用户ID">
            <el-input v-model="searchParams.user_id" placeholder="请输入用户ID"></el-input>
          </el-form-item>
          <el-form-item label="交易类型" label-width="500">
            <el-select v-model="searchParams.transaction_type" placeholder="请选择交易类型">
              <el-option v-for="option in transactionTypeOptions" :key="option" :label="option" :value="option" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="searchParams.device_type" placeholder="请选择">
              <el-option v-for="dType in deviceTypeOptions" :key="dType" :label="dType" :value="dType" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearchClick">查询</el-button>
            <el-button @click="handleResetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 交易列表 -->
        <el-table :data="transactions" stripe style="width: 100%">
          <el-table-column prop="transaction_id" label="ID" width="80" sortable />
          <el-table-column prop="user_id" label="用户ID" width="100" />
          <el-table-column prop="transaction_amount" label="金额" width="100" sortable />
          <el-table-column prop="transaction_type" label="类型" width="120" />
          <el-table-column prop="account_balance" label="账户余额" width="120" />
          <el-table-column prop="device_type" label="设备" width="120" />
          <el-table-column prop="location" label="位置" width="120" />
          <el-table-column prop="merchant_category" label="商户" width="120" />
            <el-table-column prop="fraud_label" label="欺诈" width="100">
  <template #default="{ row }">
    <el-tag :type="row.fraud_label === 0 ? 'success' : row.fraud_label === 1 ? 'danger' : 'warning'">
      {{ row.fraud_label === 0 ? '未欺诈' : row.fraud_label === 1 ? '欺诈' : '还未检测' }}
    </el-tag>
  </template>
</el-table-column>

          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="handleEditClick(row)">编辑</el-button>
              <el-button size="small" type="primary" @click="showDetail(row)">详情</el-button>
              <el-button size="small" type="primary" @click="hadlePredictClick(row)">预测</el-button>
              <el-button size="small" type="danger" @click="handleDeleteClick(row.transaction_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 表单弹窗 -->
   <!-- 表单弹窗 -->
<el-dialog v-model="showForm" :title="form.transaction_id ? '编辑交易' : '新增交易'" width="600px">
  <el-form :model="form" label-width="120px">

    <!-- 交易Id -->
    <el-form-item label="交易Id">
      <el-input v-model="form.transaction_id"  />
    </el-form-item>

    <!-- 用户ID -->
    <el-form-item label="用户ID">
      <el-input v-model="form.user_id"  />
    </el-form-item>

    <!-- 交易金额 -->
    <el-form-item label="交易金额">
      <el-input v-model="form.transaction_amount" type="number" />
    </el-form-item>

    <!-- 交易类型 -->
    <el-form-item label="交易类型">
      <el-select v-model="form.transaction_type" placeholder="请选择">
        <el-option v-for="type in transactionTypeOptions" :key="type" :label="type" :value="type" />
      </el-select>
    </el-form-item>

    <!-- 交易时间 -->
    <el-form-item label="交易时间">
      <el-date-picker
        v-model="form.transaction_timestamp"
        type="datetime"
        placeholder="请选择日期和时间"
        style="width: 100%;"
      />
    </el-form-item>

    <!-- 账户余额 -->
    <el-form-item label="账户余额">
      <el-input v-model="form.account_balance" type="number" />
    </el-form-item>

    <!-- 设备类型 -->
    <el-form-item label="设备类型">
      <el-select v-model="form.device_type" placeholder="请选择">
        <el-option v-for="dType in deviceTypeOptions" :key="dType" :label="dType" :value="dType" />
      </el-select>
    </el-form-item>

    <!-- 地理位置 -->
    <el-form-item label="地理位置">
      <el-select v-model="form.location" placeholder="请选择">
        <el-option v-for="mc in place" :key="mc" :label="mc" :value="mc" />
      </el-select>
    </el-form-item>

    <!-- 商户类型 -->
    <el-form-item label="商户类型">
      <el-select v-model="form.merchant_category" placeholder="请选择">
        <el-option v-for="mc in merchantCategoryOptions" :key="mc" :label="mc" :value="mc" />
      </el-select>
    </el-form-item>

    <!-- IP地址标记 -->
    <el-form-item label="IP地址标记">
      <el-switch v-model="form.ip_address_flag" active-value="1" inactive-value="0" />
    </el-form-item>

    <!-- 过去欺诈活动数量 -->
    <el-form-item label="过去欺诈活动数量">
      <el-input v-model="form.previous_fraudulent_activity" type="number" />
    </el-form-item>

    <!-- 当天交易数量 -->
    <el-form-item label="当天交易数量">
      <el-input v-model="form.daily_transaction_count" type="number" />
    </el-form-item>

    <!-- 7天平均交易金额 -->
    <el-form-item label="7天平均交易金额">
      <el-input v-model="form.avg_transaction_amount_7d" type="number" />
    </el-form-item>

    <!-- 7天失败交易计数 -->
    <el-form-item label="7天失败交易计数">
      <el-input v-model="form.failed_transaction_count_7d" type="number" />
    </el-form-item>

    <el-form-item label="信用卡类型">
      <el-select v-model="form.card_type" placeholder="请选择">
        <el-option v-for="mc in cardTypeOptions" :key="mc" :label="mc" :value="mc" />
      </el-select>
    </el-form-item>

    <!-- 卡龄（单位：月） -->
    <el-form-item label="卡龄（单位：月）">
      <el-input v-model="form.card_age" type="number" />
    </el-form-item>

    <!-- 交易距离（公里） -->
    <el-form-item label="交易距离（公里）">
      <el-input v-model="form.transaction_distance" type="number" />
    </el-form-item>

    <!-- 身份验证方式 -->
    <el-form-item label="身份验证方式">
      <el-input v-model="form.authentication_method" />
    </el-form-item>

    <!-- 风险评分 -->
    <el-form-item label="风险评分">
      <el-input v-model="form.risk_score" type="number" />
    </el-form-item>

    <!-- 是否周末 -->
    <el-form-item label="是否周末">
      <el-switch v-model="form.is_weekend" active-value="1" inactive-value="0" />
    </el-form-item>

  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="showForm = false">取 消</el-button>
    <el-button type="primary" @click="submitForm">确 定</el-button>
  </div>
</el-dialog>

<!--      编辑-->
      <el-dialog v-model="updateForm" :title="编辑数据" width="600px">
        <el-form :model="form" label-width="120px">
          <!-- 交易Id -->
          <el-form-item label="交易Id">
            <el-input v-model="form.transaction_id"  />
          </el-form-item>
          <!-- 用户ID -->
          <el-form-item label="用户ID">
            <el-input v-model="form.user_id"  />
          </el-form-item>

          <!-- 交易金额 -->
          <el-form-item label="交易金额">
            <el-input v-model="form.transaction_amount" type="number" />
          </el-form-item>

          <!-- 交易类型 -->
          <el-form-item label="交易类型">
            <el-select v-model="form.transaction_type" placeholder="请选择">
              <el-option v-for="type in transactionTypeOptions" :key="type" :label="type" :value="type" />
            </el-select>
          </el-form-item>

          <!-- 交易时间 -->
          <el-form-item label="交易时间">
            <el-date-picker
                v-model="form.transaction_timestamp"
                type="datetime"
                placeholder="请选择日期和时间"
                style="width: 100%;"
            />
          </el-form-item>

          <!-- 账户余额 -->
          <el-form-item label="账户余额">
            <el-input v-model="form.account_balance" type="number" />
          </el-form-item>

          <!-- 设备类型 -->
          <el-form-item label="设备类型">
            <el-select v-model="form.device_type" placeholder="请选择">
              <el-option v-for="dType in deviceTypeOptions" :key="dType" :label="dType" :value="dType" />
            </el-select>
          </el-form-item>

          <!-- 地理位置 -->
          <el-form-item label="信用卡类型">
            <el-select v-model="form.location" placeholder="请选择">
              <el-option v-for="mc in place" :key="mc" :label="mc" :value="mc" />
            </el-select>
          </el-form-item>

          <!-- 商户类型 -->
          <el-form-item label="商户类型">
            <el-select v-model="form.merchant_category" placeholder="请选择">
              <el-option v-for="mc in merchantCategoryOptions" :key="mc" :label="mc" :value="mc" />
            </el-select>
          </el-form-item>

          <!-- IP地址标记 -->
          <el-form-item label="IP地址标记">
            <el-switch v-model="form.ip_address_flag" active-value="1" inactive-value="0" />
          </el-form-item>

          <!-- 过去欺诈活动数量 -->
          <el-form-item label="过去欺诈活动数量">
            <el-input v-model="form.previous_fraudulent_activity" type="number" />
          </el-form-item>

          <!-- 当天交易数量 -->
          <el-form-item label="当天交易数量">
            <el-input v-model="form.daily_transaction_count" type="number" />
          </el-form-item>

          <!-- 7天平均交易金额 -->
          <el-form-item label="7天平均交易金额">
            <el-input v-model="form.avg_transaction_amount_7d" type="number" />
          </el-form-item>

          <!-- 7天失败交易计数 -->
          <el-form-item label="7天失败交易计数">
            <el-input v-model="form.failed_transaction_count_7d" type="number" />
          </el-form-item>

          <el-form-item label="信用卡类型">
            <el-select v-model="form.card_type" placeholder="请选择">
              <el-option v-for="mc in cardTypeOptions" :key="mc" :label="mc" :value="mc" />
            </el-select>
          </el-form-item>

          <!-- 卡龄（单位：月） -->
          <el-form-item label="卡龄（单位：月）">
            <el-input v-model="form.card_age" type="number" />
          </el-form-item>

          <!-- 交易距离（公里） -->
          <el-form-item label="交易距离（公里）">
            <el-input v-model="form.transaction_distance" type="number" />
          </el-form-item>

          <!-- 身份验证方式 -->
          <el-form-item label="身份验证方式">
            <el-input v-model="form.authentication_method" />
          </el-form-item>

          <!-- 风险评分 -->
          <el-form-item label="风险评分">
            <el-input v-model="form.risk_score" type="number" />
          </el-form-item>

          <!-- 是否周末 -->
          <el-form-item label="是否周末">
            <el-switch v-model="form.is_weekend" active-value="1" inactive-value="0" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateForm = false">取 消</el-button>
          <el-button type="primary" @click="updateTran()">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog v-model="showOpen" title="交易详情" width="600px">
        <el-descriptions border column="1">
          <el-descriptions-item label="用户ID">
            {{ form.user_id }}
          </el-descriptions-item>
          <el-descriptions-item label="交易金额">
            {{ form.transaction_amount }}
          </el-descriptions-item>
          <el-descriptions-item label="交易类型">
            {{ form.transaction_type }}
          </el-descriptions-item>
          <el-descriptions-item label="账户余额">
            {{ form.account_balance }}
          </el-descriptions-item>
          <el-descriptions-item label="设备类型">
            {{ form.device_type }}
          </el-descriptions-item>
          <el-descriptions-item label="地理位置">
            {{ form.location }}
          </el-descriptions-item>
          <el-descriptions-item label="商户类型">
            {{ form.merchant_category }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址标识">
            {{ form.ip_address_flag }}
          </el-descriptions-item>
          <el-descriptions-item label="先前欺诈行为">
            {{ form.previous_fraudulent_activity==0 ? '否' : '是' }}
          </el-descriptions-item>
          <el-descriptions-item label="每日交易次数">
            {{ form.daily_transaction_count }}
          </el-descriptions-item>
          <el-descriptions-item label="7日平均交易金额">
            {{ form.avg_transaction_amount_7d }}
          </el-descriptions-item>
          <el-descriptions-item label="7日失败交易次数">
            {{ form.failed_transaction_count_7d }}
          </el-descriptions-item>
          <el-descriptions-item label="卡类型">
            {{ form.card_type }}
          </el-descriptions-item>
          <el-descriptions-item label="卡龄">
            {{ form.card_age }}
          </el-descriptions-item>
          <el-descriptions-item label="交易距离">
            {{ form.transaction_distance }}
          </el-descriptions-item>
          <el-descriptions-item label="认证方式">
            {{ form.authentication_method }}
          </el-descriptions-item>
          <el-descriptions-item label="风险评分">
            {{ form.risk_score }}
          </el-descriptions-item>
          <el-descriptions-item label="是否周末">
            {{ form.is_weekend ==0 ? '否' : '是' }}
          </el-descriptions-item>
        </el-descriptions>

        <template #footer>
          <el-button @click="showOpen = false">关闭</el-button>
        </template>
      </el-dialog>

    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { addTransaction, deleteTransaction, getTransactions, predict, updateTransaction } from "@/api/fraud";
import { ElMessage } from "element-plus";

// 交易列表
const transactions = ref([]);
const showOpen=ref(false)
// 查询条件
const searchParams = ref({
  user_id: '',
  transaction_type: '',
  device_type: ''
});

// 用于表单的交易对象
const form = ref({
  transaction_id: null,
  user_id: '',
  transaction_amount: '',
  transaction_type: '',
  account_balance: '',
  device_type: '',
  location: '',
  merchant_category: '',
  ip_address_flag: 0,
  previous_fraudulent_activity: 0,
  daily_transaction_count: 0,
  avg_transaction_amount_7d: 0,
  failed_transaction_count_7d: 0,
  card_type: '',
  card_age: 0,
  transaction_distance: 0,
  authentication_method: '',
  risk_score: 0,
  is_weekend: 0,
});
const updateTran=async ()=>{
  await  updateTransaction(form.value.transaction_id,form.value)
  updateForm.value=false
  await fetchTransactions()
  ElMessage.success('修改成功')
}
// 是否显示创建/编辑的弹窗
const showForm = ref(false);

// 枚举选项
const transactionTypeOptions = ['Online', 'In-Store', 'ATM'];
const deviceTypeOptions = ['Mobile','Laptop','Tablet'];
const merchantCategoryOptions = [ 'Food', 'Travel'];
const cardTypeOptions = ['Mastercard', 'Discover', 'Visa','Amex'];
const authenticationMethodOptions = ['PIN', 'Biometric'];
const place = ['Sydney', 'New York','Mumbai','Tokyo','London'];

// 获取所有交易，根据查询条件进行请求
const fetchTransactions = async () => {
  try {
    // 将查询条件传入 API 请求
    const resp = await getTransactions(searchParams.value);
    transactions.value = resp;
  } catch (error) {
    ElMessage.error('获取交易列表失败，请查看控制台');
  }
};
const showDetail=(row)=>{
  form.value=row;
  showOpen.value=true;
}
// 查询按钮点击事件
const handleSearchClick = () => {
  fetchTransactions();
};

// 重置查询条件
const handleResetSearch = () => {
  searchParams.value = {
    user_id: '',
    transaction_type: '',
    device_type: ''
  };
  fetchTransactions();
};

// 点击“新增交易”按钮，清空表单并打开弹窗
const handleCreateClick = () => {
  resetForm();
  showForm.value = true;
};
const updateForm=ref(false)
// 点击“编辑”按钮，填充表单并显示
const handleEditClick = (transaction) => {
  // resetForm();
  console.log(transaction)
  form.value = { ...transaction };

  updateForm.value = true;
};

// 点击“删除”按钮
const handleDeleteClick = async (transaction_id) => {
  if (!confirm(`确认删除交易 ID = ${transaction_id} ?`)) {
    return;
  }
  try {
    await deleteTransaction(transaction_id);
    ElMessage.success(`交易 ID = ${transaction_id} 已删除`);
    fetchTransactions();
  } catch (error) {
    console.error('删除失败：', error);
    alert('删除失败，请查看控制台错误');
  }
};

// 提交表单（新增或编辑）
const submitForm = async () => {
  const payload = { ...form.value };

  // 校验 transaction_id 是否以 TXN_ 开头
  const pattern = /^TXN_/;
  if (!pattern.test(payload.transaction_id)) {
    ElMessage.error('交易ID必须以 "TXN_" 开头，请重新输入');
    return; // 中断提交流程
  }

  try {
    await addTransaction(payload);
    ElMessage.success('新增成功');
    showForm.value = false;
    await fetchTransactions();
  } catch (err) {
    ElMessage.error('新增失败，请稍后重试');
    console.error(err);
  }
};


// 重置表单内容
const resetForm = () => {
  form.value = {
    transaction_id: null,
    user_id: '',
    transaction_amount: '',
    transaction_type: 'Online',
    account_balance: '',
    device_type: 'Mobile',
    location: '',
    merchant_category: '',
    ip_address_flag: 0,
    previous_fraudulent_activity: 0,
    daily_transaction_count: 0,
    avg_transaction_amount_7d: 0,
    failed_transaction_count_7d: 0,
    card_type: '',
    card_age: 0,
    transaction_distance: 0,
    authentication_method: 'PIN',
    risk_score: 0,
    is_weekend: 0,
  };
};

const hadlePredictClick = async (row) => {
  const res = await predict(row);
  fetchTransactions();
  if (res.prediction == 1) {
    ElMessage.error(`预测结果：${res.message}`);
  } else {
    ElMessage.success(`预测结果：${res.message}`);
  }

};

// 组件加载时自动获取数据
onMounted(() => {
  fetchTransactions();
});
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-card {
  margin: 20px;
}
.el-button {
  margin-left: 5px;
}
.search-form {
  margin-bottom: 20px;
}
</style>
